// 线程同步，条件变量

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>

using namespace std;

const int num = 5;

// 初始化全局条件变量和锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* active(void* args)
{
    string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        cout << name << "：运行" << endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    // 1.创建线程
    pthread_t tid[num];
    for(int i = 0; i < num; i++)
    {
        char* name = new char[32];
        snprintf(name, 32, "thread-%d", i+1);
        pthread_create(tid + i, nullptr, active, name);
    }

    sleep(3);   //等待所有的线程都去条件变量等待

    // 主线程唤醒其他线程
    while(true)
    {
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        sleep(1);
    }

    // .接收线程
    for(int i = 0; i < num; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    return 0;
}